//
//  SAProductInventoryView.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/10/21.
//

#import "SAProductInventoryView.h"
#import "SAInventoryCollectionViewCell.h"
#import "SAProductSizeORColorModel.h"
#import "SAInventoryTableViewCell.h"
#import "SAProductChooseColorModel.h"

@interface SAProductInventoryView ()<UITableViewDataSource, UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UISwitch *mySwitch;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) NSMutableArray<SAProductChooseColorList *> *colourMArr;
@property (nonatomic, strong) NSMutableArray *sizeMArr;
@property (nonatomic, assign) NSInteger current;
@property (nonatomic, assign) CGFloat collectionViewHeight;
@property (nonatomic, assign) BOOL isMore;//开启多选
@property (nonatomic, assign) NSInteger selectNum;//计算选中的数量
@property (nonatomic, strong) NSMutableArray<SAProductChooseColorList *> *selectColourMarr;//计算选中的数量

@end

@implementation SAProductInventoryView

-(instancetype)initWithColourArr:(NSMutableArray *)colourMarr SizeArr:(NSMutableArray *)sizeMarr AndSelectArr:(NSMutableArray<SAProductSizeORColorModel *> *)selectMarr {
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.isMore = NO;
        //构造数据模型
        self.current = 0;
        if (colourMarr.count == 0) {
            SAProductChooseColorList *model = [SAProductChooseColorList new];
            model.specsAttrId = @"-1";
            model.attrName = @"均色";
            colourMarr = [NSMutableArray array];
            [colourMarr addObject:model];
        }
        if (sizeMarr.count == 0) {
            SAProductChooseColorList *model = [SAProductChooseColorList new];
            model.specsAttrId = @"-1";
            model.attrName = @"均码";
            sizeMarr = [NSMutableArray array];
            [sizeMarr addObject:model];
        }
        self.colourMArr = colourMarr;
        self.sizeMArr = [NSMutableArray array];
        for (int i = 0; i < self.colourMArr.count; i ++) {
            self.colourMArr[i].isSelecd = NO;
            NSMutableArray<SAProductChooseColorList *> *newMArr = [NSMutableArray array];
            for (int j = 0; j < sizeMarr.count; j++) {
                SAProductChooseColorList *model = [SAProductChooseColorList new];
                model.specsAttrId = [sizeMarr[j] specsAttrId];
                model.attrName =[sizeMarr[j] attrName];
                model.num = @"0";
                for (SAProductSizeORColorModel *sizeORColorMode in selectMarr) {
                    if ([model.specsAttrId isEqualToString:sizeORColorMode.sizeId] && [self.colourMArr[i].specsAttrId isEqualToString:sizeORColorMode.colorId]) {
                        model.num = sizeORColorMode.count;
                    }
                }
                [newMArr addObject:model];
            }
            [self.sizeMArr addObject:newMArr];
        }
        self.colourMArr[0].isSelecd = YES;
        [self.selectColourMarr addObject:self.colourMArr[0]];
        [self creatUI];
    }
    return self;
}

#pragma mark - UICollectionView Delegate & DataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.colourMArr.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"SAInventoryCollectionViewCell";
    SAInventoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.model = self.colourMArr[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SAProductChooseColorList *model = self.colourMArr[indexPath.row];
    if (model.isSelecd == YES && self.selectColourMarr.count == 1) {
        return;
    }
    if (self.isMore == YES) { //是否多选
        model.isSelecd = !model.isSelecd;
        self.current = indexPath.row;
        if (model.isSelecd == YES) {
            [self.selectColourMarr addObject:model];
        }else {
            [self.selectColourMarr removeObject:model];
        }
        if (self.selectColourMarr.count == 0) {
            self.current = -1;
        }
        [self.tableView reloadData];
        [self.collectionView reloadData];
    }else {
        if (self.current == -1) {
            model.isSelecd = YES;
            self.current = indexPath.row;
        }else {
            model.isSelecd = !model.isSelecd;
            if (model.isSelecd == YES) {
                self.colourMArr[self.current].isSelecd = NO;
                self.current = indexPath.row;
            }else {
                self.current = -1;
            }
        }
        [self.collectionView reloadData];
        [self.tableView reloadData];
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.current == -1) {
        return 0;
    }
    NSMutableArray *marr = self.sizeMArr[self.current];
    return marr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAInventoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAInventoryTableViewCell" forIndexPath:indexPath];
    NSInteger index = self.current;
    if (self.isMore == YES) {
        index = [self.colourMArr indexOfObject:self.selectColourMarr[0]];
    }
    NSMutableArray *marr = self.sizeMArr[index];
    SAProductChooseColorList *model = marr[indexPath.row];
    
    cell.model = model;
    __weak typeof(self) weakSelf = self;
    cell.inputBlock = ^(NSString * _Nonnull str) {
        if (weakSelf.isMore == YES) {
            for (int i = 0; i < weakSelf.selectColourMarr.count; i++) {
                NSInteger index2 = [weakSelf.colourMArr indexOfObject:weakSelf.selectColourMarr[i]];
                NSMutableArray *marr2 = weakSelf.sizeMArr[index2];
                SAProductChooseColorList *model2 = marr2[indexPath.row];
                model2.num = str;
            }
        }else {
            model.num = str;
        }
        [weakSelf combinedNum];
    };
    
    cell.addBlock = ^{
        if (weakSelf.isMore == YES) {
            for (int i = 0; i < weakSelf.selectColourMarr.count; i++) {
                NSInteger index2 = [weakSelf.colourMArr indexOfObject:weakSelf.selectColourMarr[i]];
                NSMutableArray *marr2 = weakSelf.sizeMArr[index2];
                SAProductChooseColorList *model2 = marr2[indexPath.row];
                NSInteger num = [model2.num integerValue];
                model2.num = [NSString stringWithFormat:@"%zd",num + 1];
            }
        }else {
            model.num = [NSString stringWithFormat:@"%zd",[model.num integerValue] + 1];
        }
        [weakSelf combinedNum];
    };
    
    cell.cutBlock = ^{
        if (weakSelf.isMore == YES) {
            for (int i = 0; i < weakSelf.selectColourMarr.count; i++) {
                NSInteger index2 = [weakSelf.colourMArr indexOfObject:weakSelf.selectColourMarr[i]];
                NSMutableArray *marr2 = weakSelf.sizeMArr[index2];
                SAProductChooseColorList *model2 = marr2[indexPath.row];
                NSInteger num = [model2.num integerValue];
                model2.num = [NSString stringWithFormat:@"%zd",num - 1];
            }
        }else {
            model.num = [NSString stringWithFormat:@"%zd",[model.num integerValue] - 1];
        }
        [weakSelf combinedNum];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);;
}

#pragma mark - event
- (void)switchAction:(UISwitch *) s1 {
    if (s1.on == YES) {
        self.isMore = YES;
        [self.selectColourMarr removeAllObjects];
        if (self.current != -1) {
            [self.selectColourMarr addObject:self.colourMArr[self.current]];
        }
    }else{
        self.isMore = NO;
        if (self.selectColourMarr.count == 0) {
            self.current = -1;
        }else {
            NSInteger index = [self.colourMArr indexOfObject:self.selectColourMarr[0]];
            self.current = index;
            for (SAProductChooseColorList *model in self.colourMArr) {
                model.isSelecd = NO;
            }
            self.colourMArr[self.current].isSelecd = YES;
        }
        [self.collectionView reloadData];
        [self.tableView reloadData];
    }
}

- (void)clickedConfirmBtn {
    NSMutableArray<SAProductSizeORColorModel *> *marr = [NSMutableArray array];
    for (int i = 0; i < self.colourMArr.count; i++) {
        NSMutableArray *sizeMarr = self.sizeMArr[i];
        for (SAProductChooseColorList *model in sizeMarr) {
            if (model.num.length > 0 && [model.num integerValue] != 0){
                SAProductSizeORColorModel *newModel = [SAProductSizeORColorModel new];
                newModel.colorId = self.colourMArr[i].specsAttrId;
                newModel.colorName = self.colourMArr[i].attrName;
                newModel.sizeId = model.specsAttrId;
                newModel.sizeName = model.attrName;
                newModel.count = model.num;
                [marr addObject:newModel];
            }
        }
    }
    !self.selectBlock ?: self.selectBlock(marr);
    [self shareDissTapEvent];
}

-(void)combinedNum {
    for (int i = 0; i < self.colourMArr.count; i++) {
        NSMutableArray *marr = self.sizeMArr[i];
        NSInteger num = 0;
        for (SAProductChooseColorList *model in marr) {
            num += [model.num integerValue];
        }
        self.colourMArr[i].num = @(num).stringValue;
    }
    [self.collectionView reloadData];
}

#pragma mark - creatUI
-(void)creatUI {
    
    self.userInteractionEnabled = YES;
    self.backgroundColor = kColor(0, 0, 0, 0.6);
    NSInteger count = 0;
    if (self.colourMArr.count > 5) {
        double countD = self.colourMArr.count * 1.0f / 4;
        count = ceilf(countD);
    }else {
        count = 1;
    }
    self.collectionViewHeight = count * 34 + (count - 1) * 10 + 20;
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(157));
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    [self addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    [self.headerView addSubview:self.mySwitch];
    [self.headerView addSubview:self.collectionView];
    [self addSubview:self.footerView];
    
    self.mySwitch.on = self.isMore;
}

-(void)shareDissTapEvent {
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)showView:(UIViewController *)Sview {
    if(Sview == nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

#pragma mark - lazy
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(157), kScreenWidth, kScreenHeight - kScaleNum(157 + 40) - SafeFooterHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kColor(246, 246, 246, 1);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAInventoryTableViewCell class] forCellReuseIdentifier:@"SAInventoryTableViewCell"];
    }
    return _tableView;
}

-(UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, (50 + self.collectionViewHeight))];
        _headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(30, 11, 100, 14)];
        titleLab.text = @"颜色";
        titleLab.textColor = kLightgGrayColor;
        titleLab.font = kFont(14);
        [_headerView addSubview:titleLab];
        UILabel *titleLab2 = [[UILabel alloc] initWithFrame:SARectMake(248, 11, 60, 14)];
        titleLab2.text = @"颜色多选";
        titleLab2.textColor = kLightgGrayColor;
        titleLab2.font = kFont(14);
        [_headerView addSubview:titleLab2];
    }
    return _headerView;
}

-(UISwitch *)mySwitch {
    if (!_mySwitch) {
        _mySwitch = [[UISwitch alloc] initWithFrame:SARectMake(0, 0, 0, 0)];
        _mySwitch.y = (kScaleNum(36) - _mySwitch.height)/2;
        _mySwitch.x = kScaleNum(308);
        [_mySwitch setOnTintColor:kGreenColor];
        [_mySwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _mySwitch;
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(kScaleNum(60), kScaleNum(34));
        flow.minimumInteritemSpacing = kScaleNum(10);
        //    //设置每行之间的最小间隔
        flow.minimumLineSpacing = kScaleNum(10);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(30), kScaleNum(50), kScreenWidth - kScaleNum(60), kScaleNum(self.collectionViewHeight)) collectionViewLayout:flow];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[SAInventoryCollectionViewCell class] forCellWithReuseIdentifier:@"SAInventoryCollectionViewCell"];
    }
    return _collectionView;
}

-(UIView *)footerView {
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(40) - SafeFooterHeight, kScreenWidth, kScaleNum(40) + SafeFooterHeight)];
        _footerView.backgroundColor = [UIColor whiteColor];
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
        [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        confirmBtn.frame = CGRectMake(kScreenWidth - kScaleNum(100), 0, kScaleNum(100), kScaleNum(40));
        confirmBtn.titleLabel.font = kFont(15);
        [confirmBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
        [confirmBtn addTarget:self action:@selector(clickedConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
        UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 1)];
        line.backgroundColor = kBgColor;
        [_footerView addSubview:line];
        [_footerView addSubview:confirmBtn];
    }
    return _footerView;
}

-(NSMutableArray<SAProductChooseColorList *> *)selectColourMarr {
    if (!_selectColourMarr) {
        _selectColourMarr = [NSMutableArray array];
    }
    return _selectColourMarr;
}


@end
